package com.shenmazong.service.impl;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shenmazong.pojo.TbTaskTheoryLibrary;
import com.shenmazong.service.TbTaskTheoryLibraryService;
import com.shenmazong.mapper.TbTaskTheoryLibraryMapper;
import com.shenmazong.utils.ResultResponse;
import com.shenmazong.vo.TaskTheoryListVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

/**
 *
 */
@Service
@Slf4j
public class TbTaskTheoryLibraryServiceImpl extends ServiceImpl<TbTaskTheoryLibraryMapper, TbTaskTheoryLibrary>
implements TbTaskTheoryLibraryService{
    @Autowired
    TbTaskTheoryLibraryMapper tbTaskTheoryLibraryMapper;

    @Override
    public PageInfo findTaskTheoryLibraryList(Integer pageNum, Integer pageSize, Object taskTheoryLibrary) {
        PageHelper.startPage(pageNum,pageSize);
        List<TbTaskTheoryLibrary> tbTaskTheoryLibraries=tbTaskTheoryLibraryMapper.findTaskTheoryLibraryList(taskTheoryLibrary);
        PageInfo<TbTaskTheoryLibrary> libraryPageInfo = new PageInfo<>(tbTaskTheoryLibraries);
        return libraryPageInfo;
    }

    @Override
    public ResultResponse echoTaskTheoryLibrary(TbTaskTheoryLibrary tbTaskTheoryLibrary) {
        TbTaskTheoryLibrary theoryLibrary = tbTaskTheoryLibraryMapper.echoTaskTheoryLibrary(tbTaskTheoryLibrary.getTheoryId());
        if(theoryLibrary==null){
            return ResultResponse.FAILED(-1,"回显失败");
        }
        return ResultResponse.SUCCESS(theoryLibrary);
    }

    @Override
    public ResultResponse updateTaskTheoryLibrary(TbTaskTheoryLibrary tbTaskTheoryLibrary) {
        tbTaskTheoryLibrary.setUpdateTime(new Date());
        int i = tbTaskTheoryLibraryMapper.updateById(tbTaskTheoryLibrary);
        if(i<0){
            return ResultResponse.FAILED(-1,"修改失败");
        }
        return ResultResponse.SUCCESS("修改成功");
    }

    @Override
    public ResultResponse delTaskTheoryLibrary(TbTaskTheoryLibrary tbTaskTheoryLibrary) {
        tbTaskTheoryLibraryMapper.deleteById(tbTaskTheoryLibrary.getTheoryId());
        return ResultResponse.SUCCESS("删除成功");
    }

    @Override
    public ResultResponse uploadFile(MultipartFile file) throws IOException {
        if(file==null || file.getSize()==0){
            log.info("文件为空");
            return ResultResponse.FAILED(-1,"请选择文件，重新上传");
        }
        String filename = file.getOriginalFilename();

        if(!filename.endsWith(".xls")||filename.endsWith(".xlax")){
            log.info("文件上传格式错误，重新上传");
            return ResultResponse.FAILED(-2,"文件上传格式错误，重新上传");
        }

        //构造ExcelReader对象
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        //处理别名
        reader.addHeaderAlias("知识点","knowledge");
        reader.addHeaderAlias("题干","theoryTitle");
        reader.addHeaderAlias("类型","theoryType");
        reader.addHeaderAlias("选项A","option1");
        reader.addHeaderAlias("选项B","option2");
        reader.addHeaderAlias("选项C","option3");
        reader.addHeaderAlias("选项D","option4");
        reader.addHeaderAlias("选项E","option5");
        reader.addHeaderAlias("选项F","option6");
        reader.addHeaderAlias("答案（选择填ABCDEF，中间不能有空格 判断填A或B，填空题多空用逗号分隔）","answers");
        reader.addHeaderAlias("试题解析（选填）","analysis");
        reader.addHeaderAlias("出题人","person");
        //生成list集合
        List<TbTaskTheoryLibrary> list = reader.readAll(TbTaskTheoryLibrary.class);
        //关闭流
        reader.close();
        //所有数据长度
        int size = list.size();
        log.info("文件上传成功，共"+size+"条数据");
        //数据校验
        ArrayList<TbTaskTheoryLibrary> successList = new ArrayList<>();
        ArrayList<TbTaskTheoryLibrary> errorList = new ArrayList<>();

        int nullNum=0;
        for (TbTaskTheoryLibrary library : list) {
            //读取内容为空
            if(library==null){
                nullNum++;
                continue;
            }
            //非空项为空，则加入错误集合
            if(StringUtils.checkValNull(library.getTheoryType())
                    || StringUtils.checkValNull(library.getTheoryType())
                    || StringUtils.checkValNull(library.getAnswers())){
                errorList.add(library);
                continue;
            }
            //类型内容判断
            if(!(library.getTheoryType().startsWith("1-单选") || library.getTheoryType().startsWith("2-多选") || library.getTheoryType().startsWith("0-判断") )){
                errorList.add(library);
                continue;
            }
            successList.add(library);
        }

        //错误数据集合长度
        int errorSize = errorList.size();
        //未去重长度
        int size1 = successList.size();
        HashSet<TbTaskTheoryLibrary> set = new HashSet<>(successList);
        successList.clear();
        successList.addAll(set);

        //类型内容处理
        for (TbTaskTheoryLibrary library : successList) {
            if(library.getTheoryType().startsWith("1-单选")){
                library.setTheoryType("1-单选题");
                continue;
            }
            if(library.getTheoryType().startsWith("2-多选")){
                library.setTheoryType("2-多选题");
                continue;
            }
            if(library.getTheoryType().startsWith("0-判断")){
                library.setTheoryType("0-判断题");
                continue;
            }
        }

        //去重后长度
        int size2 = successList.size();

        log.info("数据校验完成");
        String msg = "共上传 "+size+" 条数据,其中空数据"+nullNum+"条,错误数据共 "+errorSize+" 条,重复数据 "+(size1-size2)+" 条,效验通过的数据共 "+size2+" 条";

        log.info(msg);
        return ResultResponse.SUCCESS(200,msg,successList);
    }

    @Override
    public ResultResponse onLineInputTaskTheory(TaskTheoryListVo taskTheoryList) {
        List<TbTaskTheoryLibrary> list = taskTheoryList.getLibraryList();
        if(list==null){
            log.info("新增失败，数据集合为空");
            return ResultResponse.FAILED(-1,"新增失败，数据集合为空");
        }
        //遍历
        for (TbTaskTheoryLibrary theory : list) {
            //构造对象属性
            theory.setTeacherId(taskTheoryList.getTeacherId());
            theory.setChapterId(taskTheoryList.getChapterId());
            theory.setCourseId(taskTheoryList.getCourseId());
            theory.setSchoolId(taskTheoryList.getSchoolId());
            //存入数据库
            tbTaskTheoryLibraryMapper.insert(theory);
        }
        return ResultResponse.SUCCESS();
    }
}




